<template>
  <avue-crud ref="gameStockRef" :table-loading="tableLoading" v-model="form" :option="option" @refresh-change="gameList"
    @row-save="rowSave" @row-update="rowUpdate" :data="data" :page="page" @size-change="sizeChange"
    @current-change="currentChange" @search-change="searchChange" @search-reset="searchReset">
    <template #menu="{ row, index, size }">
      <el-button type="primary" text @click="look(row)">查看</el-button>
      <el-button type="primary" text @click="cfg(row)">配置</el-button>
    </template>
  </avue-crud>
  <el-dialog v-model="dialogVisible" width="100%" :before-close="handleClose" @opened="resizeChart">
    <div :class="{ 'rotate-height': isMobile }">
      <div id="main" ref="chartContainer" :style="chartStyle" :class="{ 'rotate-90': isMobile }"></div>
    </div>
  </el-dialog>
  <!-- New dialog for configuration form -->
  <el-dialog v-model="configDialogVisible_spine" width="50%" :before-close="handleConfigClose">
    <el-form :model="form" ref="formRef" label-width="120px" class="demo-ruleForm">
      <el-form-item label="InitStock" prop="InitStock">
        <el-input v-model="form.InitStock"></el-input>
      </el-form-item>
      <el-form-item label="MinCondition" prop="MinCondition">
        <el-input v-model="form.MinCondition"></el-input>
      </el-form-item>
      <el-form-item label="MaxCondition" prop="MaxCondition">
        <el-input v-model="form.MaxCondition"></el-input>
      </el-form-item>
      <el-form-item label="MaxChip" prop="MaxChip">
        <el-input v-model="form.MaxChip"></el-input>
      </el-form-item>
      <el-form-item label="StockRate" prop="StockRate">
        <el-input v-model="form.StockRate"></el-input>
      </el-form-item>
      <el-form-item label="JackPotRate" prop="JackPotRate">
        <el-input v-model="form.JackPotRate"></el-input>
      </el-form-item>
      <el-collapse v-model="activeNamesRewardRate">
        <el-collapse-item name="1">
          <template #title>
            RewardRate
          </template>
          <div v-for="(item, index) in form.RewardRate" :key="index" class="input-group">
            <el-input v-model="form.RewardRate[index]">
            </el-input>
          </div>

        </el-collapse-item>
      </el-collapse>
      <el-collapse v-model="activeNamesChips">
        <el-collapse-item name="1">
          <template #title>
            Chips
          </template>
          <div v-for="(item, index) in form.Chips" :key="index" class="input-group">
            <el-input v-model="form.Chips[index]">
            </el-input>
          </div>
        </el-collapse-item>
      </el-collapse>
      <el-collapse v-model="activeNamesStockLimit">
        <el-collapse-item name="1">
          <template #title>
            StockLimit
          </template>
          <div v-for="(item, index) in form.StockLimit" :key="index" class="input-group">
            <el-input v-model="form.StockLimit[index]">
            </el-input>
          </div>

        </el-collapse-item>
      </el-collapse>
      <el-collapse v-model="activeNames">
        <el-collapse-item v-for="(stock, stockIndex) in form.Stocks" :key="stockIndex" :name="stockIndex">
          <template #title>
            Stock {{ stockIndex + 1 }}
          </template>
          <el-form-item label="JackPotWinRate" prop="JackPotWinRate">
            <el-input v-model="stock.JackPotWinRate"></el-input>
          </el-form-item>
          <el-form-item label="JackPotHitVal" prop="JackPotHitVal">
            <el-input v-model="stock.JackPotHitVal"></el-input>
          </el-form-item>
          <el-form-item label="JackPotShowVal" prop="JackPotShowVal">
            <el-input v-model="stock.JackPotShowVal"></el-input>
          </el-form-item>
          <el-form-item label="JackPotHitRate" prop="JackPotHitRate">
            <el-input v-model="stock.JackPotHitRate"></el-input>
          </el-form-item>
          <el-form-item label="CurrentJackPot" prop="CurrentJackPot">
            <el-input v-model="stock.CurrentJackPot"></el-input>
          </el-form-item>
          <el-form-item label="CurrentStock" prop="CurrentStock">
            <el-input v-model="stock.CurrentStock"></el-input>
          </el-form-item>
          <el-collapse v-model="activeNamesStock">
            <el-collapse-item name="1">
              <template #title>
                Stock
              </template>
              <div v-for="(item, index) in stock.Stock" :key="index" class="input-group">
                <el-input v-model="stock.Stock[index]">
                </el-input>
              </div>

            </el-collapse-item>
          </el-collapse>
          <el-collapse v-model="activeNamesWeight">
            <el-collapse-item name="1">
              <template #title>
                Weight
              </template>
              <el-collapse v-model="activeNamesWeightGroup">
                <el-collapse-item v-for="(weight, weightIndex) in stock.Weight" :key="weightIndex" :name="weightIndex">
                  <template #title>
                    Weight Group {{ weightIndex + 1 }}
                  </template>
                  <div v-for="(item, index) in weight" :key="index" class="input-group">
                    <el-input v-model="weight[index]">
                    </el-input>
                  </div>

                </el-collapse-item>
              </el-collapse>
            </el-collapse-item>
          </el-collapse>
          <el-collapse v-model="activeNamesFree">
            <el-collapse-item name="1">
              <template #title>
                Free
              </template>
              <el-collapse v-model="activeNamesFreeGroup">
                <el-collapse-item v-for="(Free, weightIndex) in stock.Free" :key="weightIndex" :name="weightIndex">
                  <template #title>
                    Free Group {{ weightIndex + 1 }}
                  </template>
                  <div v-for="(item, index) in Free" :key="index" class="input-group">
                    <el-input v-model="Free[index]">
                    </el-input>
                  </div>

                </el-collapse-item>
              </el-collapse>
            </el-collapse-item>
          </el-collapse>
          <el-collapse v-model="activeNamesTryAgain">
            <el-collapse-item name="1">
              <template #title>
                TryAgain
              </template>
              <div v-for="(item, index) in stock.TryAgain" :key="index" class="input-group">
                <el-input v-model="stock.TryAgain[index]">
                </el-input>
              </div>

            </el-collapse-item>
          </el-collapse>
          <el-collapse v-model="activeNamesStockDown">
            <el-collapse-item name="1">
              <template #title>
                StockDown
              </template>
              <div v-for="(item, index) in stock.StockDown" :key="index" class="input-group">
                <el-input v-model="stock.StockDown[index]">
                </el-input>
              </div>

            </el-collapse-item>
          </el-collapse>
        </el-collapse-item>
      </el-collapse>
      <el-form-item>
        <el-button type="primary" @click="submitForm('spine')">提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <el-dialog v-model="configDialogVisible_solt" width="50%" :before-close="handleConfigClose">
    <el-form :model="form" ref="formRef" label-width="120px" class="demo-ruleForm">
      <el-collapse v-model="activeNamesGameStockConfig">
        <el-collapse-item>
          <template #title>
            jsonConf
          </template>
          <el-form-item label="GameId" prop="GameId">
            <el-input v-model="form.jsonConf.GameId"></el-input>
          </el-form-item>
          <el-form-item label="JokPotRate" prop="JokPotRate">
            <el-input v-model="form.jsonConf.JokPotRate"></el-input>
          </el-form-item>
          <el-form-item label="StockRate" prop="StockRate">
            <el-input v-model="form.jsonConf.StockRate"></el-input>
          </el-form-item>
          <el-collapse v-model="activeNamesStockV">
            <el-collapse-item v-for="(stockV, stockVIndex) in form.jsonConf.StockV" :key="stockVIndex"
              :name="stockVIndex">
              <template #title>
                StockV {{ stockVIndex + 1 }}
              </template>
              <el-form-item label="DwLevelID" prop="DwLevelID">
                <el-input v-model="stockV.DwLevelID"></el-input>
              </el-form-item>
              <el-form-item label="BIsFinish" prop="BIsFinish">
                <el-input v-model="stockV.BIsFinish"></el-input>
              </el-form-item>
              <el-form-item label="WStockIndex" prop="WStockIndex">
                <el-input v-model="stockV.WStockIndex"></el-input>
              </el-form-item>
              <el-form-item label="LlStockScore" prop="LlStockScore">
                <el-input v-model="stockV.LlStockScore"></el-input>
              </el-form-item>
              <el-form-item label="WDiffID" prop="WDiffID">
                <el-input v-model="stockV.WDiffID"></el-input>
              </el-form-item>
              <el-form-item label="IChangeRate" prop="IChangeRate">
                <el-input v-model="stockV.IChangeRate"></el-input>
              </el-form-item>
            </el-collapse-item>
          </el-collapse>

        </el-collapse-item>
        <el-collapse-item>
          <template #title>
            XmlConf
          </template>
          <el-collapse v-model="activeNamesXmlConf">
            <el-collapse-item v-for="(xmlConf, xmlConfIndex) in form.XmlConf.vcControlLevel" :key="xmlConfIndex"
              :name="xmlConfIndex">
              <template #title>
                Control Level {{ xmlConfIndex + 1 }}
              </template>
              <el-form-item label="iStcokType" prop="iStcokType">
                <el-input v-model="xmlConf.iStcokType"></el-input>
              </el-form-item>
              <el-form-item label="iCfgType" prop="iCfgType">
                <el-input v-model="xmlConf.iCfgType"></el-input>
              </el-form-item>
              <el-form-item label="iJoinRand" prop="iJoinRand">
                <el-input v-model="xmlConf.iJoinRand"></el-input>
              </el-form-item>
              <el-form-item label="vcEmptyReRand_Normal" prop="vcEmptyReRand_Normal">
                <el-input v-model="xmlConf.vcEmptyReRand_Normal"></el-input>
              </el-form-item>
              <el-form-item label="vcEmptyReRand_Free" prop="vcEmptyReRand_Free">
                <el-input v-model="xmlConf.vcEmptyReRand_Free"></el-input>
              </el-form-item>
              <el-form-item label="vcBigWinReRand_Normal" prop="vcBigWinReRand_Normal">
                <el-input v-model="xmlConf.vcBigWinReRand_Normal"></el-input>
              </el-form-item>
              <el-form-item label="vcBigWinReRand_Free" prop="vcBigWinReRand_Free">
                <el-input v-model="xmlConf.vcBigWinReRand_Free"></el-input>
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
        </el-collapse-item>
      </el-collapse>

      <el-form-item style="text-align: center;">
        <el-button style="width: 100%;" type="primary" @click="submitForm('stock')">提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick, computed } from "vue";
import gameStock_cfg from "@/options/gameStock";
import { setGamejson } from "@/apis/admin";
import * as echarts from 'echarts';
import { ElMessageBox, ElMessage } from "element-plus";
import {
  getCompanyList,
  addCompany,
  getGameStockRecords,
  getGameList,
  getGameStock,
  setGameStock,
  readsetGamejson
} from "@/apis/admin";

const dialogVisible = ref(false);
const configDialogVisible_spine = ref(false);
const configDialogVisible_solt = ref(false);
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
const chartStyle = computed(() => {
  return {
    width: isMobile ? '100%' : '100%',
    height: isMobile ? '300px' : '300px',
  };
});
const chartContainer = ref(null);
const option = gameStock_cfg;
const data = ref([]);
const page = reactive({
  total: 0,
  searchInfo: {},
  currentPage: 1,
  pageSize: 10,
});
let myChart = null;
const form = ref({});
const tableLoading = ref(false);
const activeNames = ref([]);
const activeNamesRewardRate = ref([]);
const activeNamesChips = ref([]);
const activeNamesStockLimit = ref([]);
const activeNamesStock = ref([]);
const activeNamesWeight = ref([]);
const activeNamesWeightGroup = ref([]);
const activeNamesTryAgain = ref([]);
const activeNamesFree = ref([]);
const activeNamesFreeGroup = ref([]);
const activeNamesStockDown = ref([]);
const activeNamesXmlConf = ref([]);
const activeNamesXmlVConf = ref([]);
const activeName = ref('');
const handleClose = (done) => {
  dialogVisible.value = false;
  done();
};

const handleConfigClose = (done) => {
  configDialogVisible_spine.value = false;
  configDialogVisible_solt.value = false;
  done();
};

const cfg = (row) => {
  activeName.value = row.gameCode;
  if (row.gameCode.includes('spin')) {
    setGamejson
      .post('', {
        gameCode: row.gameCode
      })
      .then((res) => {
        configDialogVisible_spine.value = true;
        form.value = JSON.parse(res.data.gameConf)
      })

  } else {
    setGamejson
      .post('', {
        gameCode: row.gameCode
      })
      .then((res) => {
        console.log(JSON.parse(res.data.gameConf))
        form.value = JSON.parse(res.data.gameConf)
        configDialogVisible_solt.value = true;

      })
    // form.value = {
    //   "jsonConf": {
    //     "GameId": 107,
    //     "JokPotRate": 0,
    //     "StockRate": 9500,
    //     "StockV": [
    //       { "DwLevelID": 1, "BIsFinish": 0, "WStockIndex": 1, "LlStockScore": 0, "WDiffID": 2, "IChangeRate": 100 },
    //       { "DwLevelID": 2, "BIsFinish": 0, "WStockIndex": 1, "LlStockScore": 20000, "WDiffID": 3, "IChangeRate": 100 },
    //       { "DwLevelID": 3, "BIsFinish": 0, "WStockIndex": 1, "LlStockScore": 25000, "WDiffID": 4, "IChangeRate": 97 },
    //       { "DwLevelID": 4, "BIsFinish": 0, "WStockIndex": 1, "LlStockScore": 30000, "WDiffID": 7, "IChangeRate": 90 },
    //       { "DwLevelID": 5, "BIsFinish": 0, "WStockIndex": 1, "LlStockScore": 37000, "WDiffID": 9, "IChangeRate": 85 },
    //       { "DwLevelID": 6, "BIsFinish": 0, "WStockIndex": 1, "LlStockScore": 45000, "WDiffID": 10, "IChangeRate": 80 },
    //       { "DwLevelID": 1, "BIsFinish": 0, "WStockIndex": 2, "LlStockScore": 0, "WDiffID": 2, "IChangeRate": 100 },
    //       { "DwLevelID": 2, "BIsFinish": 0, "WStockIndex": 2, "LlStockScore": 50000, "WDiffID": 3, "IChangeRate": 100 },
    //       { "DwLevelID": 3, "BIsFinish": 0, "WStockIndex": 2, "LlStockScore": 100000, "WDiffID": 4, "IChangeRate": 97 },
    //       { "DwLevelID": 4, "BIsFinish": 0, "WStockIndex": 2, "LlStockScore": 150000, "WDiffID": 7, "IChangeRate": 90 },
    //       { "DwLevelID": 5, "BIsFinish": 0, "WStockIndex": 2, "LlStockScore": 170000, "WDiffID": 9, "IChangeRate": 85 },
    //       { "DwLevelID": 6, "BIsFinish": 0, "WStockIndex": 2, "LlStockScore": 200000, "WDiffID": 10, "IChangeRate": 80 },
    //       { "DwLevelID": 1, "BIsFinish": 0, "WStockIndex": 3, "LlStockScore": 0, "WDiffID": 2, "IChangeRate": 100 },
    //       { "DwLevelID": 2, "BIsFinish": 0, "WStockIndex": 3, "LlStockScore": 100000, "WDiffID": 3, "IChangeRate": 100 },
    //       { "DwLevelID": 3, "BIsFinish": 0, "WStockIndex": 3, "LlStockScore": 200000, "WDiffID": 4, "IChangeRate": 97 },
    //       { "DwLevelID": 4, "BIsFinish": 0, "WStockIndex": 3, "LlStockScore": 300000, "WDiffID": 7, "IChangeRate": 90 },
    //       { "DwLevelID": 5, "BIsFinish": 0, "WStockIndex": 3, "LlStockScore": 500000, "WDiffID": 9, "IChangeRate": 85 },
    //       { "DwLevelID": 6, "BIsFinish": 0, "WStockIndex": 3, "LlStockScore": 800000, "WDiffID": 10, "IChangeRate": 80 }
    //     ]
    //   },
    //   "XmlConf": {
    //     "vcControlLevel": [{
    //       "iStcokType": 1,
    //       "iCfgType": 3,
    //       "iJoinRand": 100,
    //       "vcEmptyReRand_Normal": [0, 0, 0],
    //       "vcEmptyReRand_Free": [0, 0, 0],
    //       "vcBigWinReRand_Normal": [100, 100],
    //       "vcBigWinReRand_Free": [100, 1500]
    //     }, {
    //       "iStcokType": 2,
    //       "iCfgType": 3,
    //       "iJoinRand": 100,
    //       "vcEmptyReRand_Normal": [0, 0, 0],
    //       "vcEmptyReRand_Free": [0, 0, 0],
    //       "vcBigWinReRand_Normal": [100, 100],
    //       "vcBigWinReRand_Free": [100, 1500]
    //     }, {
    //       "iStcokType": 3,
    //       "iCfgType": 3,
    //       "iJoinRand": 75,
    //       "vcEmptyReRand_Normal": [0, 0, 0],
    //       "vcEmptyReRand_Free": [0, 0, 0],
    //       "vcBigWinReRand_Normal": [100, 150],
    //       "vcBigWinReRand_Free": [100, 1500]
    //     }, {
    //       "iStcokType": 4,
    //       "iCfgType": 3,
    //       "iJoinRand": 50,
    //       "vcEmptyReRand_Normal": [0, 0, 0],
    //       "vcEmptyReRand_Free": [0, 0, 0],
    //       "vcBigWinReRand_Normal": [100, 250],
    //       "vcBigWinReRand_Free": [100, 1500]
    //     }, {
    //       "iStcokType": 5,
    //       "iCfgType": 3,
    //       "iJoinRand": 35,
    //       "vcEmptyReRand_Normal": [0, 0, 0],
    //       "vcEmptyReRand_Free": [0, 0, 0],
    //       "vcBigWinReRand_Normal": [100, 250],
    //       "vcBigWinReRand_Free": [100, 1500]
    //     }, {
    //       "iStcokType": 6,
    //       "iCfgType": 1,
    //       "iJoinRand": 100,
    //       "vcEmptyReRand_Normal": [0, 0, 0, 0, 0, 100],
    //       "vcEmptyReRand_Free": [0, 0, 0, 0, 0, 100],
    //       "vcBigWinReRand_Normal": [100, 800],
    //       "vcBigWinReRand_Free": [100, 1500]
    //     }, {
    //       "iStcokType": 7,
    //       "iCfgType": 3,
    //       "iJoinRand": 25,
    //       "vcEmptyReRand_Normal": [0, 0, 0, 0, 0, 100],
    //       "vcEmptyReRand_Free": [0, 0, 0, 0, 0, 100],
    //       "vcBigWinReRand_Normal": [100, 600],
    //       "vcBigWinReRand_Free": [100, 1500]
    //     }, {
    //       "iStcokType": 8,
    //       "iCfgType": 3,
    //       "iJoinRand": 50,
    //       "vcEmptyReRand_Normal": [0, 0, 0, 0, 0, 100],
    //       "vcEmptyReRand_Free": [0, 0, 0, 0, 0, 100],
    //       "vcBigWinReRand_Normal": [100, 600],
    //       "vcBigWinReRand_Free": [100, 1500]
    //     }, {
    //       "iStcokType": 9,
    //       "iCfgType": 3,
    //       "iJoinRand": 75,
    //       "vcEmptyReRand_Normal": [0, 0, 0, 0, 0, 100],
    //       "vcEmptyReRand_Free": [0, 0, 0, 0, 0, 100],
    //       "vcBigWinReRand_Normal": [100, 600],
    //       "vcBigWinReRand_Free": [100, 1500]
    //     }],
    //     "vcCfg": [{
    //       "iCfgType": 1,
    //       "iJoinRand": 100,
    //       "vcEmptyReRand_Normal": [0, 0, 0],
    //       "vcEmptyReRand_Free": [0, 0, 0],
    //       "vcBigWinReRand_Normal": [100, 100],
    //       "vcBigWinReRand_Free": [100, 1500]
    //     }, {
    //       "iCfgType": 2,
    //       "iJoinRand": 100,
    //       "vcEmptyReRand_Normal": [0, 0, 0],
    //       "vcEmptyReRand_Free": [0, 0, 0],
    //       "vcBigWinReRand_Normal": [100, 100],
    //       "vcBigWinReRand_Free": [100, 1500]
    //     }, {
    //       "iCfgType": 3,
    //       "iJoinRand": 75,
    //       "vcEmptyReRand_Normal": [0, 0, 0],
    //       "vcEmptyReRand_Free": [0, 0, 0],
    //       "vcBigWinReRand_Normal": [100, 150],
    //       "vcBigWinReRand_Free": [100, 1500]
    //     }]
    //   }
    // }
  }
};

const sizeChange = (val) => {
  page.pageSize = val;
  gameList();
};
const currentChange = (val) => {
  page.currentPage = val;
  gameList();
};
const searchChange = (form, done) => {
  page.searchInfo = form;
  page.currentPage = 1;
  gameList();
  done();
};

const searchReset = () => {
  page.searchInfo = {};
  page.currentPage = 1;
  gameList();
};
const submitForm = (type, name) => {
  const convertToNumber = (obj) => {
    for (const key in obj) {
      if (typeof obj[key] === 'object' && obj[key] !== null) {
        convertToNumber(obj[key]);
      } else if (typeof obj[key] === 'string' && obj[key].includes(',')) {
        // ，
        while (obj[key].includes('，')) {
          obj[key].replace('，', ',')
        }
        obj[key] = obj[key].split(',').map(item => Number(item.trim()));
      } else if (!isNaN(obj[key]) && obj[key] !== '') {
        obj[key] = Number(obj[key]);
      }
    }
  };

  convertToNumber(form.value);

  if (type == 'spine') {
    readsetGamejson.post('', {
      gameCode: activeName.value,
      gameConf: JSON.stringify(form.value)
    }).then((res) => {
      ElMessage.success("提交成功!");
      handleConfigClose();
    })
  } else if (type == 'stock') {
    readsetGamejson.post('', {
      gameCode: activeName.value,
      gameConf: JSON.stringify({
        jsonConf: form.value.jsonConf,
        xmlConf: form.value.XmlConf
      })

    }).then((res) => {
      ElMessage.success("提交成功!");
      handleConfigClose();
    })
  }
};
const rowSave = async (row, done, loading) => {
  const res = await addCompany.post("", row);
  if (res.code == 200) {
    done();
    ElMessage.success("添加成功!");
    getList();
  } else {
    ElMessage.error("添加失败!");
  }
};
const resizeChart = () => {
  if (myChart) {
    myChart.resize();
  }
};

const postData = async (data) => {
  if (isNaN(Number(data.val)) || Number(data.val) == 0) {
    return;
  }
  return await setGameStock.post("", {
    gameCode: data.gameCode,
    changeType: data.changeType,
    index: data.index,
    value: Number(data.val) * 100
  })
}
const rowUpdate = async (row, index, done, loading) => {
  console.log(row)
  tableLoading.value = true;
  await postData({
    gameCode: row.gameCode,
    changeType: 'stock',
    index: 0,
    val: row.change_0
  })
  await postData({
    gameCode: row.gameCode,
    changeType: 'stock',
    index: 1,
    val: row.change_1
  })
  await postData({
    gameCode: row.gameCode,
    changeType: 'stock',
    index: 2,
    val: row.change_2
  })
  await postData({
    gameCode: row.gameCode,
    changeType: 'jackpot',
    index: 0,
    val: Number(row.jack_change_0) * 100
  })
  await postData({
    gameCode: row.gameCode,
    changeType: 'jackpot',
    index: 1,
    val: Number(row.jack_change_1) * 100
  })
  await postData({
    gameCode: row.gameCode,
    changeType: 'jackpot',
    index: 2,
    val: Number(row.jack_change_2) * 100
  })
  ElMessage.success("操作成功!");
  gameList();
  tableLoading.value = false;
  done();
};
const look = async (row) => {
  dialogVisible.value = true;
  console.log(row)
  nextTick(() => {
    initChart(row.gameCode);
  });
}
const initChart = (name) => {

  getGameStockRecords
    .post('', {
      gameCode: name
    })
    .then((res) => {
      let list = res.data.lists;
      if (chartContainer.value) {
        myChart = echarts.init(chartContainer.value, 'dark');
        // Prepare series data
        let totalLength = list[0].stocks.length;
        if (totalLength < 240) {
          const missingLength = 240 - totalLength;
          for (let i = 0; i < list.length; i++) {
            for (let j = 0; j < missingLength; j++) {
              list[i].stocks.unshift({
                stocks: 0,
                time: 0
              });
            }
          }
          totalLength = 240;
        }
        const seriesData = list.map((item, index) => ({
          smooth: true,
          name: item.gameCode.includes(':') ? item.gameCode.replace(':0', ':小').replace(':1', ':中').replace(':2', ':大') : item.gameCode,
          type: 'line',
          data: item.stocks.map(value => value.stocks / 100) // Divide each value by 100
        }));
        // Calculate the interval for xAxis labels

        const interval = Math.ceil(totalLength / 24); // 24 hours in a day
        // 绘制图表
        myChart.setOption({
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: list.map(item => item.gameCode.includes(':') ? item.gameCode.replace(':0', ':小').replace(':1', ':中').replace(':2', ':大') : item.gameCode),
            selected: list.reduce((acc, item) => {
              acc[item.gameCode] = false;
              return acc;
            }, {}),
            top: isMobile ? 0 : 0
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true,
            top: 0
          },
          toolbox: isMobile ? {} : {
            feature: {
              saveAsImage: {},
              dataZoom: {},
              dataView: {},
              restore: {},
              magicType: {
                type: ['line', 'bar']
              },
              myFullScreen: {
                show: true,
                title: '全屏',
                icon: 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891',
                onclick: () => {
                  const element = chartContainer.value;
                  if (element) {
                    if (document.fullscreenElement) {
                      document.exitFullscreen();
                    } else {
                      if (element.requestFullscreen) {
                        element.requestFullscreen();
                      } else if (element.webkitRequestFullscreen) { // Safari
                        element.webkitRequestFullscreen();
                      } else if (element.msRequestFullscreen) { // IE11
                        element.msRequestFullscreen();
                      } else if (element.mozRequestFullScreen) { // Firefox
                        element.mozRequestFullScreen();
                      } else if (element.webkitEnterFullscreen) { // iOS Safari
                        element.webkitEnterFullscreen();
                      }
                    }
                  }
                  // 强制触发resize事件，确保图表在全屏后正确渲染
                  setTimeout(() => {
                    window.dispatchEvent(new Event('resize'));
                  }, 100);
                }
              }
            },
            right: 0,
            top: 20,
            orient: 'horizontal'
          },
          dataZoom: [
            {
              type: 'slider',
              show: true,
              xAxisIndex: [0],
              start: 0,
              end: 100
            },
            {
              type: 'inside',
              xAxisIndex: [0],
              start: 0,
              end: 100
            }
          ],
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: list[0].stocks.map(stock => {
              const date = new Date(stock.time * 1000); // Convert timestamp to milliseconds
              date.setUTCHours(date.getUTCHours() + 8); // Convert to Beijing Time
              const hours = date.getUTCHours().toString().padStart(2, '0');
              const minutes = date.getUTCMinutes().toString().padStart(2, '0');
              return `${hours}:${minutes}`;
            })
          },
          yAxis: {
            type: 'value',
            min: (value) => value.min - value.max * 0.25,
            max: (value) => value.max * 1.25
          },
          series: seriesData
        });

        // Add click event listener to legend
        myChart.on('legendselectchanged', function (params) {
          const selectedSeriesNames = Object.keys(params.selected).filter(name => params.selected[name]);
          if (selectedSeriesNames.length > 0) {
            const selectedData = selectedSeriesNames.flatMap(name => {
              const series = seriesData.find(series => series.name === name);
              return series ? series.data : [];
            });
            let minValue = Math.min(...selectedData);
            let maxValue = Math.max(...selectedData);
            if (minValue === maxValue) {
              minValue -= 1;
              maxValue += 1;
            }
            myChart.setOption({
              yAxis: {
                min: minValue - maxValue * 0.25,
                max: maxValue * 1.25
              }
            });
            // Force refresh the chart to ensure it updates immediately
            setTimeout(() => {
              myChart.resize();
            }, 100);
          }
        });

        console.log('myChart init >>>')
      }
    })
};
const gameList = () => {
  tableLoading.value = true;
  getGameList.post("", {
    searchInfo: { company: "GameCoca" },
    page: page.currentPage,
    pageSize: page.pageSize,
    orderKey: "created_at",
    orderType: "desc",
  })
    .then(async (res) => {
      if (res.code == 200) {
        page.total = res.data.total;
        // data.value = res.data.list || [];
        console.log('游戏列表', res.data.list)
        let dataList = [];
        for (let i = 0; i < res.data.list.length; i++) {
          let gameCode = res.data.list[i].gameCode
          let data = await async_getGameStock(gameCode);
          dataList.push({
            $cellEdit: true,
            gameCode: gameCode,
            id: i,
            jackPot_0: data.jackPot[0] / 10000,
            jack_change_0: 0,
            jackPot_1: data.jackPot[1] / 10000,
            jack_change_1: 0,
            jackPot_2: data.jackPot[2] / 10000,
            jack_change_2: 0,
            // 库存
            stocks_0: data.stocks[0] / 100,
            change_0: 0,
            stocks_1: data.stocks[1] / 100,
            change_1: 0,
            stocks_2: data.stocks[2] / 100,
            change_2: 0,
          })
        }
        data.value = dataList || [];
      }
      tableLoading.value = false;
    });
}
const async_getGameStock = async (gameCode) => {
  let data = await getGameStock.post("", {
    gameCode: gameCode
  })
  return data.data
}
onMounted(() => {
  // getList();
  gameList()
  window.addEventListener('resize', resizeChart);
});
onUnmounted(() => {
  window.removeEventListener('resize', resizeChart);
  if (myChart) {
    myChart.dispose();
  }
});
</script>